import { createRouter, createWebHistory } from 'vue-router'
import { useUserStore } from '@/stores/user'
import VideoResource from '@/views/resources/VideoResource.vue'
import Login from '@/views/auth/Login.vue'
import Register from '@/views/auth/Register.vue'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      name: 'Home',
      component: () => import('@/views/Home.vue'),
      meta: { requiresAuth: false }
    },
    {
      path: '/login',
      name: 'Login',
      component: Login,
      meta: { requiresAuth: false }
    },
    {
      path: '/register',
      name: 'Register',
      component: Register,
      meta: { requiresAuth: false }
    },
    {
      path: '/teacher',
      component: () => import('../views/teacher/TeacherLayout.vue'),
      meta: { requiresAuth: true, roles: ['1'] },
      children: [
        {
          path: 'dashboard',
          name: 'TeacherDashboard',
          component: () => import('../views/Dashboard.vue'),
          meta: { title: '教师仪表盘', requiresAuth: true, roles: ['1'] }
        },
        {
          path: 'profile',
          name: 'TeacherProfile',
          component: () => import('../views/Profile.vue'),
          meta: { requiresAuth: true, title: '个人信息设置', roles: ['1'] }
        },
        {
          path: '',
          redirect: '/teacher/dashboard'
        }
      ]
    },
    {
      path: '/design',
      component: () => import('../views/design/DesignLayout.vue'),
      redirect: '/design/new',
      meta: { requiresAuth: true, roles: ['1'] },
      children: [
        {
          path: 'new',
          name: 'NewDesign',
          component: () => import('../views/design/NewDesign.vue'),
          meta: { title: '新建教学设计', requiresAuth: true, roles: ['1'] }
        },
        {
          path: 'history',
          name: 'DesignHistory',
          component: () => import('../views/design/DesignHistory.vue'),
          meta: { title: '历史教学设计', requiresAuth: true, roles: ['1'] }
        }
      ]
    },
    {
      path: '/study',
      component: () => import('@/views/study/AnalysisLayout.vue'),
      redirect: '/study/analysis',
      meta: { requiresAuth: true, roles: ['1'] },
      children: [
        {
          path: 'analysis',
          name: 'Analysis',
          component: () => import('@/views/study/Analysis.vue'),
          meta: { title: '学情分析', requiresAuth: true, roles: ['1'] }
        },
        {
          path: 'per-learn-case/:studentId',
          name: 'PerLearnCase',
          component: () => import('@/views/study/PerLearnCase.vue'),
          meta: { title: '单个学生学情', requiresAuth: true, roles: ['1'] }
        },
        {
          path: 'mul-learn-case',
          name: 'MulLearnCase',
          component: () => import('@/views/study/MulLearnCase.vue'),
          meta: { title: '批量学情分析', requiresAuth: true, roles: ['1'] },
        }
      ]
    },
    {
      path: '/resources',
      component: () => import('@/views/resources/ResourceLayout.vue'),
      meta: { requiresAuth: true, roles: ['1'] },
      children: [
        {
          path: 'video',
          name: 'VideoResource',
          component: () => import('@/views/resources/VideoResource.vue'),
          meta: {
            title: '视频资源',
            requiresAuth: true,
            roles: ['1']
          }
        },
        {
          path: 'audio',
          name: 'AudioResource',
          component: () => import('@/views/resources/AudioResource.vue'),
          meta: {
            title: '音频资源',
            requiresAuth: true,
            roles: ['1']
          }
        },
        {
          path: 'image',
          name: 'ImageResource',
          component: () => import('@/views/resources/ImageResource.vue'),
          meta: {
            title: '图片资源',
            requiresAuth: true,
            roles: ['1']
          }
        },
        {
          path: 'multimedia/history',
          name: 'MultimediaHistory',
          component: () => import('@/views/resources/MultimediaHistory.vue'),
          meta: {
            title: '多媒体资源历史记录',
            requiresAuth: true,
            roles: ['1']
          }
        },
        {
          path: '',
          redirect: '/resources/video'
        }
      ]
    },
    {
      path: '/homework',
      component: () => import('@/views/homework/HomeworkLayout.vue'),
      redirect: '/homework/generator',
      meta: { requiresAuth: true, roles: ['1'] },
      children: [
        {
          path: 'generator',
          name: 'HomeworkGenerator',
          component: () => import('@/views/homework/HomeworkGenerator.vue'),
          meta: { title: '习题生成', requiresAuth: true, roles: ['1'] }
        },
        {
          path: 'history',
          name: 'HomeworkHistory',
          component: () => import('@/views/homework/HomeworkHistory.vue'),
          meta: { title: '历史记录', requiresAuth: true, roles: ['1'] }
        }
      ]
    },
    {
      path: '/student',
      component: () => import('@/views/student/StudentLayout.vue'),
      meta: { requiresAuth: true, roles: ['2'] },
      children: [
        {
          path: 'dashboard',
          name: 'StudentDashboard',
          component: () => import('@/views/student/Dashboard.vue'),
          meta: { title: '学习仪表盘', requiresAuth: true, roles: ['2'] }
        },
        {
          path: 'errors',
          name: 'StudentErrors',
          component: () => import('@/views/student/ErrorBook.vue'),
          meta: { title: '错题本', requiresAuth: true, roles: ['2'] }
        },
        {
          path: 'assessment',
          name: 'StudentAssessment',
          component: () => import('@/views/student/Assessment.vue'),
          meta: { title: '能力评估', requiresAuth: true, roles: ['2'] }
        },
        {
          path: 'assistant',
          name: 'StudentAssistant',
          component: () => import('@/views/student/Assistant.vue'),
          meta: { title: 'AI助手', requiresAuth: true, roles: ['2'] }
        },
        {
          path: 'practice',
          name: 'StudentPractice',
          component: () => import('@/views/student/Practice.vue'),
          meta: { title: '练习学习', requiresAuth: true, roles: ['2'] }
        }
      ]
    },
    {
      path: '/admin',
      component: () => import('@/views/admin/AdminLayout.vue'),
      meta: { requiresAuth: true, roles: ['3'] },
      children: [
        {
          path: 'dashboard',
          name: 'AdminDashboard',
          component: () => import('@/views/admin/Dashboard.vue'),
          meta: { title: '管理员仪表盘', requiresAuth: true, roles: ['3'] }
        },
        {
          path: 'teachers',
          name: 'TeacherManagement',
          component: () => import('@/views/admin/TeacherManagement.vue'),
          meta: { title: '教师管理', requiresAuth: true, roles: ['3'] }
        },
        {
          path: 'teacher/add',
          name: 'AddTeacher',
          component: () => import('@/views/admin/AddTeacher.vue'),
          meta: { title: '添加教师', requiresAuth: true, roles: ['3'] }
        },
        {
          path: 'teacher/edit/:id',
          name: 'EditTeacher',
          component: () => import('@/views/admin/EditTeacher.vue'),
          meta: { title: '编辑教师', requiresAuth: true, roles: ['3'] }
        },
        {
          path: 'students',
          name: 'StudentManagement',
          component: () => import('@/views/admin/StudentManagement.vue'),
          meta: { title: '学生管理', requiresAuth: true, roles: ['3'] }
        },
        {
          path: 'student/add',
          name: 'AddStudent',
          component: () => import('@/views/admin/AddStudent.vue'),
          meta: { title: '添加学生', requiresAuth: true, roles: ['3'] }
        },
        {
          path: 'student/edit/:id',
          name: 'EditStudent',
          component: () => import('@/views/admin/EditStudent.vue'),
          meta: { title: '编辑学生', requiresAuth: true, roles: ['3'] }
        },
        {
          path: 'classes',
          name: 'ClassManagement',
          component: () => import('@/views/admin/ClassManagement.vue'),
          meta: { title: '班级管理', requiresAuth: true, roles: ['3'] }
        },
        {
          path: 'class/add',
          name: 'AddClass',
          component: () => import('@/views/admin/AddClass.vue'),
          meta: { title: '添加班级', requiresAuth: true, roles: ['3'] }
        },
        {
          path: 'class/edit/:id',
          name: 'EditClass',
          component: () => import('@/views/admin/EditClass.vue'),
          meta: { title: '编辑班级', requiresAuth: true, roles: ['3'] }
        },
        {
          path: 'statistics',
          name: 'Statistics',
          component: () => import('@/views/admin/Statistics.vue'),
          meta: { title: '数据统计', requiresAuth: true, roles: ['3'] }
        },
        {
          path: 'profile',
          name: 'AdminProfile',
          component: () => import('@/views/Profile.vue'),
          meta: { requiresAuth: true, title: '个人信息设置', roles: ['3'] }
        },
        {
          path: '',
          redirect: '/admin/dashboard'
        }
      ]
    },
    // 以下是独立路由，移动到教师布局下
    {
      path: '/dashboard',
      redirect: '/teacher/dashboard'
    },
    {
      path: '/profile',
      redirect: '/teacher/profile'
    }
  ]
})

// 全局前置守卫
router.beforeEach((to, from, next) => {
  const token = localStorage.getItem('token');
  const userRole = localStorage.getItem('userRole');
  
  // 检查路由是否需要认证
  if (to.meta.requiresAuth) {
    if (!token) {
      // 如果没有token，重定向到登录页
      next({ path: '/login' });
      return;
    }
    
    // 检查用户角色权限
    if (to.meta.roles && !to.meta.roles.includes(userRole)) {
      // 如果用户角色不匹配，重定向到对应的首页
      if (userRole === '1') {
        next({ path: '/design/new' });
      } else if (userRole === '2') {
        next({ path: '/student/dashboard' });
      } else if (userRole === '3') {
        next({ path: '/admin/dashboard' });
      } else {
        next({ path: '/' });
      }
      return;
    }
  }
  
  // 如果已登录且访问登录页，重定向到对应的首页
  if (token && to.path === '/login') {
    if (userRole === '1') {
      next({ path: '/design/new' });
    } else if (userRole === '2') {
      next({ path: '/student/dashboard' });
    } else if (userRole === '3') {
      next({ path: '/admin/dashboard' });
    } else {
      next({ path: '/' });
    }
    return;
  }
  
  next();
})

export default router